package com.tmall.wireless.virtualviewdemo.slice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.libra.expr.compiler.api.ViewCompilerApi;
import com.libra.virtualview.compiler.config.ConfigManager;
import com.tmall.wireless.vaf.expr.engine.utils.Toast;
import com.tmall.wireless.vaf.virtualview.core.IContainer;
import com.tmall.wireless.vaf.virtualview.core.Layout;
import com.tmall.wireless.virtualviewdemo.MyApplication;
import com.tmall.wireless.virtualviewdemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;

import java.io.*;

public class ParserDemoAbilitySlice extends AbilitySlice {

    private static final String TYPE = "PLAY_VV";
    private static final String PLAY = "component_demo/virtualview.xml";
//    private static final String PLAY = "component_demo/nratiolayout.xml";
    private static final String PLAY_DATA = "component_demo/virtualview.json";
    private static final String CONFIG = "config.properties";

    private Button mDoParse;
    private DirectionalLayout mLinearLayout;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_parser_demo);
        initView();
    }

    private void initView() {
        mDoParse = (Button) findComponentById(ResourceTable.Id_parse);
        mLinearLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_container);
        mDoParse.setClickedListener(component -> {
            paseJosn();
        });
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }


    private void paseJosn() {
        byte[] binResult = compile(TYPE, PLAY, 1);
        if (binResult != null) {
            MyApplication.getInstance().getViewManager().loadBinBufferSync(binResult);
            Component container = MyApplication.getInstance().getVafContext().getContainerService().getContainer(TYPE, true);
            IContainer iContainer = (IContainer) container;
            JSONObject json = getJSONDataFromAsset(PLAY_DATA);
            if (json != null) {
                iContainer.getVirtualView().setVData(json);
            }
            Layout.Params p = iContainer.getVirtualView().getComLayoutParams();
            DirectionalLayout.LayoutConfig marginLayoutParams = new DirectionalLayout.LayoutConfig(p.mLayoutWidth, p.mLayoutHeight);
            marginLayoutParams.setMarginLeft(p.mLayoutMarginLeft);
            marginLayoutParams.setMarginTop(p.mLayoutMarginTop);
            marginLayoutParams.setMarginRight(p.mLayoutMarginRight);
            marginLayoutParams.setMarginBottom(p.mLayoutMarginBottom);

            mLinearLayout.removeAllComponents();
            mLinearLayout.addComponent(container, marginLayoutParams);

        } else {
            Toast.showShort(this, "编译出错，检查日志");
        }
    }

    private JSONObject getJSONDataFromAsset(String name) {
        try {
            String filePath = String.format("assets/app/resources/rawfile/%s", name);
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
            BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = inputStreamReader.readLine()) != null) {
                sb.append(str);
            }
            inputStreamReader.close();
            return JSON.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    private byte[] compile(String type, String name, int version) {
        ViewCompilerApi viewCompiler = new ViewCompilerApi();
        viewCompiler.setConfigLoader(new AssetConfigLoader());
        InputStream fis = null;
        try {
            String filePath = String.format("assets/app/resources/rawfile/%s", name);
            fis = this.getClass().getClassLoader().getResourceAsStream(filePath);

            byte[] result = viewCompiler.compile(fis, type, version);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private class AssetConfigLoader implements ConfigManager.ConfigLoader {

        @Override
        public InputStream getConfigResource() {
            try {
                String filePath = String.format("assets/app/resources/rawfile/%s", CONFIG);
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
                return inputStream;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

}
